package udes.assassin;

import udes.assassin.server.api.Message.Message;
import android.os.AsyncTask;
import android.util.Log;

public class ApplyMessageTask extends AsyncTask<Integer, Integer, Integer> {
	MessageManager manager;
	AssassinApplication app;
	boolean stoped = false;
	
	public boolean isStoped() {
		return stoped;  
	}

	public void stop() {
		stoped = true;
		//cancel(true);
	}

	public ApplyMessageTask(MessageManager manager, AssassinApplication app)
	{
		System.out.println("Creating a task for :: " + manager.getClass().getSimpleName());
		this.manager = manager;
		this.app = app;
	}
	
	protected Integer doInBackground(Integer... nothing) {

        while(!stoped)
        {
	       	if(app != null && app.mIncomingMessageQueue != null)
    		{
	       		synchronized (app.mIncomingMessageQueue) 
	       		{
	     			if(app.mIncomingMessageQueue.size() > 0){
	     				publishProgress(1);
	     			}
	     		}
        	}
    		try {
				Thread.sleep(10); 
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }

		System.out.println("Ending a task for :: " + manager.getClass().getSimpleName());
		return 1;
     }

     protected void onProgressUpdate(Integer... progress) {
			if(app.mIncomingMessageQueue.size() > 0){

				Message mess = app.mIncomingMessageQueue.remove(0);
				Log.d("Apply", mess.getClass().getSimpleName() + " >> " + manager.getClass().getSimpleName());
				if(!manager.manage(mess))
				{
					//app.mIncomingMessageQueue.add(mess);
				}
			}
     }

     protected void onPostExecute(Integer result) {}
 }